import React, { useEffect, useState } from 'react';
import {
  Divider,
  Modal,
  Popconfirm,
  Table,
  Tooltip,
  Button,
  message,
} from 'antd';
import {
  btnPermission,
  diffSubmitData,
  formatDate,
  formatDateTimeStamp,
  mergeLoading,
} from '@/utils/utils';
import { history } from '@@/core/history';
import { PlusOutlined, FormOutlined, DeleteOutlined } from '@ant-design/icons';
import { useRequest, useUpdateEffect } from '@umijs/hooks';
import {
  apiPurchasePaymentDetailGetList,
  apiPurchasePaymentDetailAdd,
  apiPurchasePaymentDetailUpdate,
  apiPurchasePaymentDetailDelete,
  apiPurchaseReceivedInvoiceDetailGetList,
  apiPurchaseReceivedInvoiceDetailAdd,
  apiPurchaseReceivedInvoiceDetailUpdate,
  apiPurchaseReceivedInvoiceDetailDelete,
} from '@/services/otherServices';
import Detail from '@/pages/procurementManageDetail/ticketModalDetail';
import moment from 'moment';

interface Props {
  visible: boolean;
  onCancel: (e: React.MouseEvent<HTMLElement>) => void;
  record: any;
  afterClose: any;
}

let detailForm: any = null;

export default (props: Props) => {
  // props
  const { visible, onCancel, record, afterClose } = props;
  // state
  const [dataSource, setDataSource] = useState([]);
  const [current, setCurrent] = useState(1);
  const [total, setTotal] = useState(0);

  const [editId, setEditId] = useState(undefined);
  const [editItem, setEditItem] = useState(undefined);

  const [recordData, setRecordData] = useState(undefined);
  const [detailVisible, setDetailVisible] = useState(false);

  // ------ 请求 start-----

  /* 列表 */
  const { loading: pageLoading, run: getPage } = useRequest(
    apiPurchaseReceivedInvoiceDetailGetList,
    {
      manual: true,
      debounceInterval: 500,
      onSuccess: (res, params) => {
        setDataSource(res.data);
        setTotal(res.total);
      },
    },
  );

  /* 新建 */
  const { loading: addLoading, run: add } = useRequest(
    apiPurchaseReceivedInvoiceDetailAdd,
    {
      manual: true,
      debounceInterval: 500,
      loadingDelay: 200,
      onSuccess: (res, params: any) => {
        message.success('添加成功');
        setDetailVisible(false);
        getPageData();
      },
    },
  );

  /* 编辑 */
  const { loading: updateLoading, run: update } = useRequest(
    apiPurchaseReceivedInvoiceDetailUpdate,
    {
      manual: true,
      debounceInterval: 500,
      loadingDelay: 200,
      onSuccess: (res, params: any) => {
        message.success('更新成功');
        setDetailVisible(false);
        getPageData();
      },
    },
  );

  /* 删除 */
  const { loading: delLoading, run: del } = useRequest(
    apiPurchaseReceivedInvoiceDetailDelete,
    {
      manual: true,
      loadingDelay: 200,
      onSuccess: (res, params) => {
        message.success('删除成功');
        if (total % 10 === 1) {
          setCurrent(current - 1);
        } else {
          getPageData();
        }
      },
    },
  );
  // ------ 请求 end-------

  // ------ 生命周期 start-----
  useUpdateEffect(() => {
    getPageData();
  }, [current]);

  useEffect(() => {
    if (visible && dataSource.length === 0) {
      getPageData();
    }
  }, [visible]);
  // ------ 生命周期 end-------

  const getPageData = () => {
    getPage({
      // purchaseId:2,
      purchaseId: record.id,
      pageNo: current,
      pageSize: 10,
    });
  };
  const columns: any = [
    {
      title: '编号',
      dataIndex: 'a',
      width: 80,
      fixed: 'left',
      hideInSearch: true,
      render: (text: string, record: any, index: number) => (
        <span>{(current - 1) * 10 + index + 1}</span>
      ),
    },
    {
      title: '到票日期',
      dataIndex: 'receivedInvoiceTime',
      render: (text: string) => <span>{formatDate(text)}</span>,
    },
    {
      title: '发票金额',
      dataIndex: 'receivedInvoiceAmount',
    },
    {
      title: '录入人',
      dataIndex: 'entryClerk',
    },
  ];
  if (
    btnPermission(history.location.pathname, [
      'btn_purchase_received_invoice_edit',
      'btn_purchase_received_invoice_del',
    ])
  ) {
    columns.push({
      title: '操作',
      dataIndex: 'option',
      width: 120,
      fixed: 'right',
      valueType: 'option',
      render: (_: string, record: any) => (
        <>
          {btnPermission(
            history.location.pathname,
            'btn_purchase_received_invoice_edit',
          ) && (
            <span>
              <a
                onClick={() => {
                  if (record.receivedInvoiceTime) {
                    record.receivedInvoiceTime = moment(
                      record.receivedInvoiceTime,
                    );
                  }
                  detailForm.setFieldsValue({
                    ...record,
                  });
                  setDetailVisible(true);
                  setEditId(record.id);
                  setEditItem(record);
                }}
              >
                <Tooltip mouseEnterDelay={0.5} title="编辑">
                  <FormOutlined style={{ fontSize: 18 }} />
                </Tooltip>
              </a>
            </span>
          )}
          {btnPermission(
            history.location.pathname,
            'btn_purchase_received_invoice_del',
          ) && (
            <span>
              <Divider type="vertical" />
              <Popconfirm
                title="确认删除？"
                placement="topRight"
                okText="确认"
                cancelText="取消"
                onConfirm={() => {
                  del(record.id);
                }}
              >
                <a>
                  <Tooltip mouseEnterDelay={0.5} title="删除">
                    <DeleteOutlined style={{ fontSize: 18 }} />
                  </Tooltip>
                </a>
              </Popconfirm>
            </span>
          )}
        </>
      ),
    });
  }
  return (
    <Modal
      title="到票详情"
      width={1024}
      visible={visible}
      onCancel={onCancel}
      footer={null}
      afterClose={afterClose}
    >
      <div style={{ textAlign: 'right', marginBottom: 8 }}>
        <Detail
          afterClose={() => {
            setEditId(undefined);
            setEditItem(undefined);
            setRecordData(undefined);
            detailForm.resetFields();
          }}
          visible={detailVisible}
          editId={editId}
          getForm={(from: any) => (detailForm = from)}
          loading={mergeLoading(addLoading, updateLoading)}
          onCancel={() => setDetailVisible(false)}
          onOk={async () => {
            await detailForm.validateFields();
            const value = detailForm.getFieldsValue();
            if (value.receivedInvoiceTime) {
              value.receivedInvoiceTime = formatDateTimeStamp(
                value.receivedInvoiceTime,
              );
            }
            if (value.receivedInvoice) {
              value.receivedInvoice = value.receivedInvoice === 1;
            }
            if (value.multiplePayment) {
              value.multiplePayment = value.multiplePayment === 1;
            }
            if (editId) {
              const data = diffSubmitData(editItem, value);

              update({
                id: editId,
                ...data,
              });
            } else {
              add({
                purchaseId: record.id,
                ...value,
              });
            }
          }}
        />
        {btnPermission(
          history.location.pathname,
          'btn_purchase_received_invoice_add',
        ) && (
          <Button
            onClick={() => setDetailVisible(true)}
            icon={<PlusOutlined />}
            style={{ minWidth: 80 }}
            type="primary"
          >
            新建
          </Button>
        )}
      </div>
      <Table
        rowKey={'id'}
        loading={pageLoading}
        dataSource={dataSource}
        columns={columns}
        pagination={{
          pageSize: 10,
          total: total,
          current: current,
          onChange: (page, pageSize) => {
            setCurrent(page);
          },
          onShowSizeChange: (current, size) => {
            setCurrent(current);
          },
        }}
      />
    </Modal>
  );
};
